/*
 * @Author: 最爱白菜吖 <1355081829@qq.com>
 * @Date: 2022-09-23 20:19:53
 * @LastEditTime: 2022-09-24 23:22:58
 * @LastEditors: 最爱白菜吖
 * @FilePath: \electron-vite-vue\electron\main.js
 * @QQ: 大前端QQ交流群: 473246571
 * @公众账号: 乐编码
 * 惑而不从师，其为惑也，终不解矣
 * Copyright (c) 2022 by 武汉跃码教育, All Rights Reserved.
 */
const { app, BrowserWindow, session } = require("electron");
const path = require("path");
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

const NODE_ENV = process.env.NODE_ENV;
let mainWindow;

function createWindow() {
	mainWindow = new BrowserWindow({
		width: 800,
		height: 600,
		transparent: true,
		icon: path.resolve(__dirname, "favicon_256.ico"),
		webPreferences: {
			preload: path.join(__dirname, "preload.js"),
		},
	});

	// win.loadFile("index.html");
	mainWindow.loadURL(
		NODE_ENV === "development"
			? "http://localhost:5173"
			: `file://${path.join(__dirname, "../dist/index.html")}`
	);
	// 打开开发工具
	if (NODE_ENV === "development") {
		mainWindow.webContents.openDevTools();
	}
}
const reactDevToolsPath = path.join(
	__dirname,
	"vue-devtool/nhdogjmejiglipccpnnnanhbledajbpd/6.2.1_0"
);

app.whenReady().then(async () => {
	// 添加 Vue.js devtools
	// 请忽略控制台警告，后面插件更新了再更新
	await session.defaultSession.loadExtension(reactDevToolsPath);
	createWindow();
	mainWindow.webContents.session.webRequest.onBeforeSendHeaders(
		(details, callback) => {
			callback({
				requestHeaders: { Origin: "*", ...details.requestHeaders },
			});
		}
	);

	mainWindow.webContents.session.webRequest.onHeadersReceived(
		(details, callback) => {
			callback({
				responseHeaders: {
					"Access-Control-Allow-Origin": ["*"],
					...details.responseHeaders,
				},
			});
		}
	);
	app.on("activate", () => {
		if (BrowserWindow.getAllWindows().length === 0) {
			createWindow();
		}
	});
});

app.on("window-all-closed", () => {
	if (process.platform !== "darwin") {
		app.quit();
	}
});
